package com.yenlien.traceyun.milk.service;

import com.yenlien.traceyun.milk.dao.FarmersDao;
import com.yenlien.traceyun.milk.entity.Farmers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2022/7/11
 * @Author jiaLong
 * @Descript
 */
@Service
public class FarmersService {

    @Autowired
    private FarmersDao farmersDao;


    public Farmers save(Farmers farmers) {
        return farmersDao.save(farmers);
    }

    public List<Farmers> findAll() {
        return farmersDao.findAll();
    }


    public Page<Farmers> findByList(Farmers farmers) {
        Pageable pageable = PageRequest.of(farmers.getPage(), farmers.getPageSize(), Sort.Direction.DESC, "createtime");
        return farmersDao.findAll((Root<Farmers> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
            List<Predicate> list = new ArrayList<>();
            if (!StringUtils.isEmpty(farmers.getCompanyId())) {
                list.add(cb.equal(root.get("companyId"), farmers.getCompanyId()));
            }
            if (!StringUtils.isEmpty(farmers.getFarmersName())) {
                list.add(cb.like(root.get("farmersName"), "%" + farmers.getFarmersName() + "%"));
            }
            if (!StringUtils.isEmpty(farmers.getFarmersPhone())) {
                list.add(cb.equal(root.get("farmersPhone"), "%" + farmers.getFarmersPhone() + "%"));
            }
            if (!StringUtils.isEmpty(farmers.getState())) {
                list.add(cb.equal(root.get("state"), farmers.getCompanyId()));
            }
            Predicate[] predicate = new Predicate[list.size()];
            return cb.and(list.toArray(predicate));
        }, pageable);
    }







}
